<template>
  <div
    class="message-bell"
    @click.stop=""
    :class="[showModal ? 'show-message-modal' : '']"
    v-if="memberStore.profile"
  >
    <div @click="showModalFunc" class="bell-message-container">
      <svg
        t="1740021378117"
        class="yindu-icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="6903"
        width="16"
        height="16"
      >
        <path
          d="M905.832448 713.386667c-37.546667-46.08-88.746667-109.226667-88.746667-175.786667V327.68C817.085781 146.773333 682.259115 0 509.885781 0S204.904448 146.773333 204.904448 327.68v209.92c0 64.853333-56.32 126.293333-90.453333 172.373333-32.426667 42.666667-56.32 76.8-39.253334 109.226667 15.36 29.013333 52.906667 34.133333 83.626667 34.133333h180.906667a170.666667 170.666667 0 0 0 341.333333 0h187.733333c18.773333 0 64.853333 0 80.213334-32.426666S939.965781 756.053333 905.832448 713.386667zM510.397781 957.44a103.424 103.424 0 0 1-104.106666-104.106667h208.213333a103.424 103.424 0 0 1-104.106667 104.106667z m358.4-172.373333H143.464448c6.826667-10.24 17.066667-23.893333 23.893333-34.133334 39.253333-52.906667 104.106667-126.293333 104.106667-213.333333V327.68c0-143.36 102.4-259.413333 237.226667-259.413333s238.933333 116.053333 238.933333 259.413333v209.92c0 90.453333 59.733333 165.546667 104.106667 218.453333 6.826667 8.533333 17.066667 20.48 23.893333 29.013334z"
          fill="#1B1B1B"
          p-id="6904"
        ></path>
      </svg>
      <div class="no_read_count" v-if="unreadCount > 0">{{ unreadCount }}</div>
    </div>
    <div class="message-modal">
      <h2 class="message-title">
        <span class="left">{{ $t("tag.bell_message") }}</span>
        <!-- <span class="right" v-if="unreadCount == 0">{{
          $t("tag.bell_message_all_read")
        }}</span>
        <span class="right" v-else>{{
          $t("tag.bell_message_unread").replace("%num", unreadCount)
        }}</span> -->
      </h2>
      <template v-if="messages">
        <div class="message-list yindu-scrollbar" @scroll="handleScroll">
          <div
            v-for="(message, index) in messages"
            :key="index"
            class="message-item"
            :class="{ unread: !message.read }"
          >
            <div class="message-content">
              <div class="message-header">
                <span class="message-type">{{ message.type }}</span>
                <span class="message-time">{{ formatTime(message.time) }}</span>
              </div>
            </div>
          </div>
          <div v-if="loading" class="loading-indicator">加载中...</div>
        </div>
      </template>
      <template v-else>
        <div
          class="message-list"
          style="display: flex; align-items: center; justify-content: center"
        >
          <LoadingOutlined class="loading-icon" />
        </div>
      </template>
      <!-- <footer>
        <span>查看更多</span>
        <IconMore class="svg-icon" fill="var(--yd-primary-color)" />
      </footer> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  watch,
  watchEffect,
} from "vue";
import { Modal as AModal, Badge as ABadge, message } from "ant-design-vue";
import ShowMore from "~/components/ShowMore.vue";
import { postUserMessageList, postUserMessageNoReadCount } from "~/api/member";
import { useMemberStore } from "../../../../store";
import { useNuxtApp } from "nuxt/app";
const memberStore = useMemberStore();

interface Message {
  id: number;
  type: string;
  content: string;
  time: string;
  read: boolean;
}

const showModal = ref(false);
const messages = ref<Message[]>();
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const loading = ref(false);

const { $emits, $on } = useNuxtApp();

$on("other-nav-show", () => {
  showModal.value = false;
});

const showModalFunc = () => {
  showModal.value = !showModal.value;
  if (showModal.value) {
    $emits("bell-nav-show");
  }
  if (unreadCount.value == 0 && messages.value) return;
  loadLatestData();
};

watchEffect(() => {
  if (process.client) {
    if (!isMobile()) return;
    const appHeader = document.querySelector("#app-header") as HTMLElement;
    if (appHeader) {
      if (showModal.value) {
        appHeader.style.position = "fixed";
        document.body.style.paddingTop = "var(--yd-header-height)";
      } else {
        document.body.style.paddingTop = "0";
        appHeader.style.position = "sticky";
      }
    }
  }
});

async function loadLatestData() {
  let res = await postUserMessageList({ page: 1 });
  let messageList = res.data.data.map((item) => {
    return {
      id: item.id,
      type: item.pm_name,
      time: item.create_time,
      read: false,
    };
  });
  unreadCount.value = 0;
  messages.value = messageList;
}

// 获取未读消息数量
const unreadCount = ref();
// 格式化时间显示
const formatTime = (time: string) => {
  return new Date(time).toLocaleString();
};

// 加载更多消息
const loadMoreMessages = async () => {
  if (totalCount.value && totalCount.value < currentPage.value) return;
  if (loading.value) return;
  loading.value = true;
  try {
    const newMessages = await fetchMessages(currentPage.value, pageSize.value);
    if (newMessages.length > 0) {
      currentPage.value++;
      messages.value = [...messages.value, ...newMessages];
    }
  } finally {
    loading.value = false;
  }
};

// 模拟获取消息的API
const fetchMessages = async (
  page: number,
  size: number
): Promise<Message[]> => {
  return new Promise(async (resolve) => {
    let res = await postUserMessageList({ page });
    let messageList = res.data.data.map((item) => {
      return {
        id: item.id,
        type: item.pm_name,
        time: item.create_time,
        read: false,
      };
    });
    totalCount.value = res.data.last_page;
    resolve(messageList);
  });
};

// 获取未读消息数量
const getUnreadCount = async () => {
  let res = await postUserMessageNoReadCount();
  unreadCount.value = res.num;
  if (res.num >= 100) {
    unreadCount.value = "99";
  }
};

// Add scroll event listener to message list
const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement;
  const bottom = target.scrollHeight - target.scrollTop === target.clientHeight;
  if (bottom) {
    loadMoreMessages();
  }
};

getUnreadCount();
if (process.client) {
  setInterval(() => {
    getUnreadCount();
  }, 1000 * 30);
}
onMounted(() => {
  window.addEventListener("click", () => {
    showModal.value = false;
  });
  window.addEventListener("resize", () => {
    if (isMobile()) {
      showModal.value = false;
    }
  });
  const messageList = document.querySelector(".message-list");
  if (messageList) {
    messageList.addEventListener("scroll", handleScroll);
  }
});

onBeforeUnmount(() => {
  const messageList = document.querySelector(".message-list");
  if (messageList) {
    messageList.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style lang="less" scoped>
.message-bell {
  position: relative;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
  margin-right: 24px;

  &:hover {
    background-color: #f5f5f5;
  }

  .yindu-icon {
    display: block;
    width: 20px;
    height: 20px;
  }
  &.show-message-modal .message-modal {
    visibility: visible;
    opacity: 1;
    transform: translateY(0);
  }
  .bell-message-container {
    position: relative;
    .no_read_count {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(50%, -50%);
      width: 22px;
      line-height: 22px;
      height: 22px;
      box-sizing: content-box;
      background-color: #f00;
      border-radius: 50%;
      font-size: 12px;
      text-align: center;
      color: #fff;
    }
  }
}
.loading-icon {
  font-size: 30px;
}
:deep(.showMoreVue) .show-more-scroll {
  margin: 0 !important;
}
.message-modal {
  border: 1px solid #f0f0f0;
  position: absolute;
  top: 42px;
  transition: all 0.3s;
  opacity: 0;
  transform: translateY(15px);
  visibility: hidden;
  right: 0;
  z-index: 1;
  display: flex;
  flex-direction: column;
  width: 320px;
  height: 400px;
  // height: 400px;
  background-color: #fff;
  box-shadow: 0 4px 8px 0 var(--cb-color-shadow, rgba(0, 0, 0, 0.16));
  .message-title {
    font-size: 14px;
    font-weight: 500;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // .left {
    //   font-size: 16px;
    // }
    // .right {
    //   font-size: 12px;
    // }
  }

  .message-list {
    flex: 1;
    overflow-y: auto;
    .message-item {
      padding: 8px 12px;
      transition: background-color 0.3s;
      &:hover {
        background-color: #f3f5f6;
      }

      .message-header {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 14px;
        gap: 5px;
        .message-type {
          font-weight: 500;
          color: #333;
          word-break: break-word;
        }

        .message-time {
          font-size: 12px;
          color: rgb(128, 128, 128);
        }
      }
    }
  }
}
footer {
  font-size: 14px;
  padding: 12px;
  border-top: 1px solid #f0f0f0;
  color: var(--yd-primary-color);
  display: flex;
  align-items: center;
}
.loading-indicator {
  text-align: center;
  padding: 10px;
  color: #999;
  font-size: 14px;
}

@media screen and (max-width: 768px) {
  .message-bell {
    &.show-message-modal .message-modal {
      transform: translateX(0);
    }
  }
  .bell-message-container {
    .yindu-icon {
      width: 82px;
      height: 82px;
    }
    .no_read_count {
      width: 72px !important;
      height: 72px !important;
      font-size: 48px !important;
      line-height: 72px !important;
    }
  }
  .message-modal {
    position: fixed;
    left: 0;
    background-color: #fff;
    right: 0;
    top: var(--yd-header-height);
    height: calc(100vh - var(--yd-header-height));
    width: 100%;
    z-index: 1000;
    box-shadow: none;
    opacity: 1;
    transform: translateX(100%) translateY(0);
    visibility: visible;
    .message-title {
      font-size: 72px;
      padding: 64px 82px;
      border-color: #ced8e0;
    }
    .message-list {
      .message-item {
        padding: 64px 82px;
        .message-header {
          font-size: 72px;
          gap: 40px;
          .message-time {
            font-size: 54px;
          }
        }
      }
    }
  }
}
</style>
